package com.qd.panda.service.commodity.excel;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.park.domain.commodity.CommodityClassificationDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.model.CommodityClassification;
import com.qd.panda.service.commodity.CommodityClassificationService;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 商品分类,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
@RequiredArgsConstructor
public class CommodityClassificationImportHandler {

    private final CommodityClassificationService commodityClassificationService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;

    private final LocalDateTime now = LocalDateTime.now();

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<CommodityClassificationDTO>> rowList, List<BatchResult> results) {
        final List<CommodityClassificationDTO> commodityClassificationList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> existsIds = existsIds(commodityClassificationList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<CommodityClassificationDTO> excelRowMsg : rowList) {
                final CommodityClassificationDTO commodityClassificationDTO = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDTO(commodityClassificationDTO);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<CommodityClassification> addCommodityClassificationList = new ArrayList<>(size);
                final List<CommodityClassification> updateCommodityClassificationList = new ArrayList<>(size);
                doProcessDictData(existsIds, commodityClassificationList, addCommodityClassificationList, updateCommodityClassificationList);
                BatchResult.buildBatchResult(results, addCommodityClassificationList.size(), updateCommodityClassificationList.size());
                addCommodityClassificationList.clear();
                updateCommodityClassificationList.clear();
            }
        } finally {
            commodityClassificationList.clear();
            existsIds.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsIds            已经存在的数据库主键
     * @param commodityClassificationList       excel行数据集合
     * @param addCommodityClassificationList    添加集合
     * @param updateCommodityClassificationList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<CommodityClassificationDTO> commodityClassificationList, List<CommodityClassification> addCommodityClassificationList, List<CommodityClassification> updateCommodityClassificationList) {
        String orgId = SecurityUtils.getLoginUser().getCurrentOrgId();
        String personId = SecurityUtils.getLoginUser().getUserId();
        commodityClassificationList.forEach(commodityClassificationDTO -> {
            final CommodityClassification commodityClassification = commodityClassificationService.dtoToModel(commodityClassificationDTO);
            commodityClassification.setOrgId(orgId);
            commodityClassification.setOperator(personId);
            commodityClassificationService.clearCache(commodityClassification);
            if (MbUtil.isExistInCollection(existsIds, commodityClassification.getClassificationCode())) {
                commodityClassification.setAddTime(null);
                commodityClassification.setUpdateTime(now);
                updateCommodityClassificationList.add(commodityClassification);
            } else {
                commodityClassification.setAddTime(now);
                commodityClassification.setUpdateTime(null);
                addCommodityClassificationList.add(commodityClassification);
            }
            commodityClassificationDTO.freeData();
        });
        if (!addCommodityClassificationList.isEmpty()) {
            commodityClassificationService.saveBatch(addCommodityClassificationList);
        }
        if (!updateCommodityClassificationList.isEmpty()) {
            commodityClassificationService.updateBatchIds(updateCommodityClassificationList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param commodityClassificationList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<CommodityClassificationDTO> commodityClassificationList) {
        final List<String> ids = commodityClassificationList.stream().map(CommodityClassificationDTO::getClassificationCode).collect(toList());
        final List<String> existsIds = commodityClassificationService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param commodityClassificationDTO 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDTO(CommodityClassificationDTO commodityClassificationDTO) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        importValidate(commodityClassificationDTO, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param commodityClassificationDTO 单个excel行数据
     * @param errors      异常信息存储
     */
    private void importValidate(CommodityClassificationDTO commodityClassificationDTO, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(commodityClassificationDTO, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}